#!/bin/bash
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
####位置自检
if [ ! $(command -v yunzai-file) ];then
echo -e "$0: 脚本位置不在PATH环境，拒绝运行"
exit 1
fi
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
yunzai run inss jq
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#-_-# 用以存储yunzai插件所需文件,和yunzai关系不大
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#以base64编码形式存储文件
versions=1.2.0
times=2023/10/25
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
data=$BASH_SANDBOX_ROOTDIR/etc/data/yunzai.base64.files.json
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#### 检查数据库
if [ ! -f $data ];then
echo -e "$0: 找不到数据库文件，拒绝运行"
exit 1
fi
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
file_list=($(jq -r '.files | keys' $data | sed 's/^\[//;s/^\]//;s/,$//;s/"//g'))
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
case $1 in
opt)
[ -z 3 ]&&echo Null&&exit 0
shopt -s nocasematch
Item=()
Sequence=()
for i in "${!file_list[@]}"; do
  if [[ ${file_list[$i]} =~ ^$2 ]]; then
    Item+=(${file_list[$i]})
    Sequence+=($i)
  fi
done
#过滤
Sequence=${Sequence[0]}
if [[ ${#Item[@]} = 0 ]];then
  echo Null
elif [[ ${#Item[@]} > 1 ]];then
  echo Null
elif [[ ${#Item[@]} = 1 ]] ;then
  if [ -z $3 ];then
    jq -r ".files.${Item[@]} | .base64" $data | sed 's/ /\n/g' | base64 -d
  else
    jq -r ".files.${Item[@]} | .base64" $data | sed 's/ /\n/g' | base64 -d > $3/$(jq -r ".files.${Item[@]} | .type" $data)
  fi
fi;;
ls)for i in ${file_list[@]};do echo ${i};done;;
help)echo "用法: yunzai-file [命令]
opt [项目]      释放项目文件
ls              列出所有项目
help            显示此帮助"
esac